rm(list = ls())

## THIS SCRIPT: levels (upper part of TABLE A1)

library(tidyverse)
library(kableExtra)

## Custom function to summarize vector

summarize_vec <- function(vector){
  
  mean_v <- mean(vector, na.rm = T)
  median_v <- median(vector, na.rm = T)
  sd_v <- sd(vector, na.rm = T)
  n_obs <- length(vector[!is.na(vector)])
  min_v <- min(vector, na.rm = T)
  max_v <- max(vector, na.rm = T)
  
  
  data.frame(cbind(mean_v, median_v, sd_v, n_obs, min_v, max_v))
  
}


## Load Data

btw <- readRDS('data/data_main.RDS') %>%
  ungroup() %>%
  mutate(covar_pop_total = covar_pop_total/1000,
         covar_gdp_pc = covar_gdp_pc/1000)


covars <- c('spd_zweit', 
            'cdu_csu_zweit', 
            'greens_zweit', 
            'fdp_zweit', 
            'left_zweit', 
            'other_zweit',
            'turnout', 
            'decrease_laste', 
            'polar_bund_alt', 
            'east', 
            'covar_pop_total', 
            'covar_gdp_pc')

labels <- c('SPD vote share', 
            'CDU/CSU vote share', 
            'Greens vote share', 
            'FDP vote share', 
            'Left party vote share', 
            'Other parties vote share',
            'Turnout', 
            'Newspaper exit (0/1)', 
            'Electoral polarization', 
            'East Germany (0/1)', 
            'Population size (thousands)', 
            'GDP per capita (thousands)')


## Summarize 

dat <- btw %>% 
  dplyr::select(one_of(covars)) %>%
  mutate_all(as.numeric)

summary_all <- apply(dat, 2, summarize_vec) %>%
  reduce(rbind) %>%
  mutate_all(round, 2) %>%
  mutate(label = labels) %>%
  dplyr::select(label, everything())

names(summary_all) <- c('Variable', 'Mean', 'Median', 'S.D.', 'N', 'Min', 'Max')

# To Tex Table 

summary_all %>%
  kableExtra::kable(., format = 'latex', 
                    booktabs = T,
                    linesep = "",
                    caption = 'Summary statistics, federal election data') %>%
  kable_styling(latex_options = c("hold_position", 'scale_down'), 
                position = "center") 





